import { cloneDeep } from "lodash-es";
import type {Result} from "@/api/http/types";

/**
 * 通用分页配置
 */
export interface PaginationConfig {
  total: number;
  current: number;
  pageSize: number;
  pageSizeOptions: string[];
  showSizeChanger: boolean;
  showQuickJumper: boolean;
  showTotal: Function;
}

/**
 * 分页默认配置
 */
export const defaultPagination: PaginationConfig = {
  total: 0,
  current: 1,
  pageSize: 10,
  pageSizeOptions: ["10", "20", "50"],
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => {
    return `总计 ${total} 条记录`;
  },
};

/**
 * 分页表格
 */
const useTablePage = (params: Object, loadFun: Function, formatFun?: Function) => {
  const tableLoading = ref<boolean>(true);
  const pageInfo = reactive<PaginationConfig>(cloneDeep(defaultPagination));
  const paging = reactive({
    current: 1,
    size: pageInfo.pageSize
  });

  const tableDataSource = ref([]);
  const handleLoadData = () => {
    tableLoading.value = true;

    loadFun(Object.assign(params, paging))
      .then((response: Result) => {
        if (formatFun) {
          tableDataSource.value = formatFun(response.data.records);
        } else {
          tableDataSource.value = response.data.records;
        }
        pageInfo.total = response.data.total;
        pageInfo.current = response.data.current;
        pageInfo.pageSize = response.data.size;
      })
      .catch((error: any) => {
        console.error(error);
      })
      .finally(() => {
        tableLoading.value = false;
      });
  };

  const handlePageChange = (page: PaginationConfig) => {
    paging.current = page.current;
    paging.size = page.pageSize;
    handleLoadData();
  };

  //搜索
  const handleSearch = () => {
    paging.current = 1;
    handleLoadData();
  };

  return {
    tableLoading,
    pageInfo,
    paging,
    tableDataSource,
    handleLoadData,
    handlePageChange,
    handleSearch
  };
};

export default useTablePage;
